package com.tanhua.dubbo.huanxin.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tanhua.dubbo.huanxin.config.HuanXinConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String redisKey = "HX_TOKEN";

    @Autowired
    private HuanXinConfig huanXinConfig;

    /**
     * 从redis中获取环信token,如果过期需要重新获取
     * @return
     */
    public String getToken() {
        String token = this.redisTemplate.opsForValue().get(redisKey);
        if(StrUtil.isNotEmpty(token)) {
            return token;
        }

        //如果token不存在,重新获取
        return this.refreshToken();
    }

    /**
     * 如果token过期或不存在,重新获取token
     * @return
     */
    public String refreshToken() {

        //{org_name}/{app_name}/token
        //请求url
        String url = StrUtil.format("{}/{}/{}/token",
                this.huanXinConfig.getUrl(),
                this.huanXinConfig.getOrgName(),
                this.huanXinConfig.getAppName());
        //请求参数
        Map<String, String> param = new HashMap<>();
        param.put("grant_type", "client_credentials");
        param.put("client_id", this.huanXinConfig.getClientId());
        param.put("client_secret", this.huanXinConfig.getClientSecret());

        //Hutool的restful请求
        HttpResponse response = HttpRequest.post(url)
                .timeout(10000)
                .body(JSONUtil.toJsonStr(param))
                .execute();
        if(response.isOk()) {
            //获取token成功
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String access_token = jsonObject.getStr("access_token");
            Long expires_in = jsonObject.getLong("expires_in") - 3600;
            //将token进行缓存
            this.redisTemplate.opsForValue().set(redisKey, access_token, expires_in, TimeUnit.SECONDS);
            return access_token;
        }

        //重新获取失败
        return null;
    }
}
